//
//  StorageBrandViewController.m
//  danpin
//
//  Created by chuangjia on 15/12/2015.
//  Copyright © 2015 chuangjia. All rights reserved.
//

#import "StorageBrandViewController.h"
#import "StorageInfo.h"
#import "StorageBrandsCell.h"
@interface StorageBrandViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    
}
@property(nonatomic,strong)UITableView *tbview;
@property(nonatomic,strong)NSMutableArray *itemDatas;
@property(nonatomic,strong)NSMutableDictionary *sectionArray;
@end

@implementation StorageBrandViewController
@synthesize currentCategory1=_currentCategory1;
@synthesize currentCategory2=_currentCategory2;
@synthesize currentCategory3=_currentCategory3;
@synthesize currentCategoryName=_currentCategoryName;
- (void)viewDidLoad {
    [super viewDidLoad];
    [UMengShare event:CK_JIANHUOBRAND acc:1];
    // Do any additional setup after loading the view.
    if (_currentCategoryName.length>0) {
          self.navTitle = [NSString stringWithFormat:@"%@ | 热门品牌",_currentCategoryName];
    }else{
       self.navTitle = @"热门品牌";
    }
    
    self.isIndex = NO;
    if (!_itemDatas) {
        _itemDatas =[[NSMutableArray alloc] init];
    }
    if (!_sectionArray) {
        _sectionArray = [[NSMutableDictionary alloc] init];
    }
    [self initUI];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)dealloc
{
    self.actionBlock =nil;
    self.itemDatas = nil;
}
-(void)setCallBack:(void(^)(UIView*,id,id,id))callback
{
    self.actionBlock =callback;
}
-(void)initUI
{
    if (_tbview) {
        _tbview.dataSource=nil;
        _tbview.delegate =nil;
        [_tbview removeFromSuperview];
        _tbview=nil;
    }
    _tbview = [[UITableView alloc] initWithFrame:CGRectMake(0,hightAuto(65), self.view.bounds.size.width, self.view.bounds.size.height-hightAuto(65)) style:UITableViewStylePlain];
    _tbview.delegate = self;
    _tbview.dataSource = self;
    _tbview.backgroundColor =[UIColor colorWithRed:0.967 green:0.967 blue:0.967 alpha:1];
    _tbview.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    _tbview.showsHorizontalScrollIndicator = NO;
    _tbview.showsVerticalScrollIndicator = NO;
    _tbview.scrollsToTop = YES;
    [self.view addSubview:_tbview];
    [self getBrands];
}
#pragma mark - tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.itemDatas.count;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{;
    if (section>=self.itemDatas.count) {
        return 0;
    }
    NSDictionary *item = [self.itemDatas objectAtIndex:section];
    if (item && [item isKindOfClass:[NSDictionary class]]) {
        NSArray *keystr =[item allKeys];
        NSString *key = [keystr objectAtIndex:0];
        id itemarray =[item objectForKey:key];
        if (itemarray && [itemarray isKindOfClass:[NSArray class]]) {
            return [itemarray count];
        }
    }
   
    return 0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}
-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (section>=self.itemDatas.count) {
        return @"";
    }
    NSDictionary *item = [self.itemDatas objectAtIndex:section];
    if (item && [item isKindOfClass:[NSDictionary class]]) {
        NSArray *keystr =[item allKeys];
        NSString *key = [keystr objectAtIndex:0];
        return key;
    }
    return @"";
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}
- ( NSArray *)sectionIndexTitlesForTableView:( UITableView *)tableView
{
    NSArray *myKeyss = [self.sectionArray allKeys];
    NSArray *sortedKeys = [myKeyss sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
    NSMutableArray *myKeys = [NSMutableArray arrayWithArray:sortedKeys];//;
    if ([myKeys containsObject:@"#"]) {
        [myKeys removeObject:@"#"];
        [myKeys insertObject:@"#" atIndex:[myKeys count]];
    }
    return myKeys ;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [StorageBrandsCell returnCellHeight:nil];
    
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    StorageBrandsCell *cell = (StorageBrandsCell*)[tableView  dequeueReusableCellWithIdentifier:@"StorageBrandsCell"];
    if(cell == nil)
    {
        cell = [[StorageBrandsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"StorageBrandsCell"];//一定要重用啊，否则用户订单多了会卡死的
        cell.backgroundColor=[UIColor whiteColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
   
    if (indexPath.section>=self.itemDatas.count) {
        return cell;
    }
    NSDictionary *item = [self.itemDatas objectAtIndex:indexPath.section];
    if (item && [item isKindOfClass:[NSDictionary class]]) {
        NSArray *keystr =[item allKeys];
        NSString *key = [keystr objectAtIndex:0];
        id itemarray =[item objectForKey:key];
        if (itemarray && [itemarray isKindOfClass:[NSArray class]]) {
            if (indexPath.row >= [itemarray count]) {
                return cell;
            }
            NSDictionary *dict = [itemarray objectAtIndex:indexPath.row];
            [cell showInfo:dict key:@"StorageBrandsCell" indexPath:indexPath];
        }
    }
    
  
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section>=self.itemDatas.count) {
        return;
    }
    NSDictionary *item = [self.itemDatas objectAtIndex:indexPath.section];
    if (item && [item isKindOfClass:[NSDictionary class]]) {
        NSArray *keystr =[item allKeys];
        NSString *key = [keystr objectAtIndex:0];
        id itemarray =[item objectForKey:key];
        if (itemarray && [itemarray isKindOfClass:[NSArray class]]) {
            if (indexPath.row >= [itemarray count]) {
                return;
            }
            NSDictionary *dict = [itemarray objectAtIndex:indexPath.row];
            if (self.actionBlock) {
                self.actionBlock(self.view,dict,@"StorageBrandsCell",indexPath);
            }
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
  
}
//====================================================
//
//====================================================
-(void)getBrands
{
    NSMutableDictionary *dict =[NSMutableDictionary dictionary];
    [dict setValue:self.currentCategory1 forKey:@"cate1"];
    [dict setValue:self.currentCategory2 forKey:@"cate2"];
    [dict setValue:self.currentCategory3 forKey:@"cate3"];
    [ZShare showAnimationView:self.view center:self.view.center];
    __weak typeof (self) wSelf = self;
    [StorageInfo getBrands:dict success:^(AFHTTPRequestOperation *operation, id result) {
        [wSelf parserResultObject:result];
        [ZShare hiddenAnimationView:wSelf.view];
    } failure:^(NSError *error) {
        [ZShare hiddenAnimationView:wSelf.view text:@""];
    }];
}
-(void)parserResultObject:(id)resultObject
{
    [ZShare hiddenAnimationView:self.view];
    if (resultObject==nil) {
        return;
    }
    if (resultObject && [resultObject isKindOfClass:[NSDictionary class]])
    {
        id data =  [resultObject objectForKey:@"brands"];
        if (data && [data isKindOfClass:[NSDictionary class]]){
            [self.itemDatas removeAllObjects];
            
            [self.sectionArray removeAllObjects];
            self.sectionArray = [NSMutableDictionary dictionaryWithDictionary:data];
            
            NSArray *myKeyss = [self.sectionArray allKeys];
            NSArray *sortedKeys = [myKeyss sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
            NSMutableArray *myKeys = [NSMutableArray arrayWithArray:sortedKeys];//;
            if ([myKeys containsObject:@"#"]) {
                [myKeys removeObject:@"#"];
                [myKeys insertObject:@"#" atIndex:[myKeys count]];
            }
            
            for (NSString* keyv in myKeys) {
                id tdata = [self.sectionArray  objectForKey:keyv];
                NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:tdata,keyv, nil];
                [self.itemDatas addObject:dict];
            }
        }
//        BOOL  isLoadFinished=  [[resultObject objectForKey:@"end"] boolValue];
        
        if (YES)
        {
            NSString *end_msg =[resultObject objectForKey:@"end_msg"];
            self.tbview.tableFooterView =[ZShare footerView:end_msg];
        }
    }
    [self.tbview reloadData];
}

@end
